package com.bagus.mediapipefacedetection.ctrl;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.Rect;
import android.util.Log;

import com.bagus.mediapipefacedetection.application.BaseApplication;
import com.bagus.mediapipefacedetection.jni.FaceDetectJni;
import com.bagus.mediapipefacedetection.quality.DetectQualityInfo;
import com.bagus.mediapipefacedetection.utils.ImageUtil;
import com.google.mediapipe.components.CameraHelper;
import com.google.mediapipe.formats.proto.LandmarkProto;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.List;


public class FaceDetectCtrl {
    private static final String FOCAL_LENGTH_STREAM_NAME = "focal_length_pixel";
    private static final String OUTPUT_LANDMARKS_STREAM_NAME = "face_landmarks_with_iris";
    private static final String BINARY_GRAPH_NAME = "iris_tracking_gpu.binarypb";
    private static final String INPUT_VIDEO_STREAM_NAME = "input_video";
    private static final String OUTPUT_VIDEO_STREAM_NAME = "output_video";
    private static final CameraHelper.CameraFacing CAMERA_FACING = CameraHelper.CameraFacing.FRONT;
    private static final boolean FLIP_FRAMES_VERTICALLY = true;
    private FaceDetectJni faceDetectJni = null;
    private boolean isStop;
    private long handle = 0;

    static {
        System.loadLibrary("mediapipe_jni");
        System.loadLibrary("opencv_java3");
        System.loadLibrary("detectFace");
    }

    public FaceDetectCtrl() {
        faceDetectJni = new FaceDetectJni();
    }

    //    public boolean init(byte[] trackModel, byte[] mouthModel, byte[] eyeModel, byte[] poseModel, byte[] blurModel) {
//        synchronized (FaceDetectCtrl.class) {
//            Log.e("FaceDetectCtrl", "init");
//            if (handle != 0) {
//                return false;
//            }
//            handle = faceDetectJni.nativeInit();
//            if (handle != 0) {
//                return faceDetectJni.nativeLoadModels(handle, trackModel, mouthModel, eyeModel, poseModel, blurModel);
//            }
//            return false;
//        }
//    }
//
//    public void release() {
//        synchronized (FaceDetectCtrl.class) {
//            Log.e("FaceDetectCtrl", "release");
//            if (handle == 0) {
//                return;
//            }
//            faceDetectJni.nativeRelease(handle);
//            handle = 0;
//        }
//    }
//
//    public void startDetect() {
//        synchronized (FaceDetectCtrl.class) {
//            Log.e("FaceDetectCtrl", "startDetect");
//            if (handle == 0) {
//                return;
//            }
//            faceDetectJni.startDetectFace(handle);
//        }
//    }
//
    public void stopDetect() {
        synchronized (FaceDetectCtrl.class) {
            Log.e("FaceDetectCtrl", "stopDetect");
            if (handle == 0) {
                return;
            }
//            faceDetectJni.nativeStopDetect(handle);
            isStop = true;
        }
    }
//
//    public void reset() {
//        synchronized (FaceDetectCtrl.class) {
//            Log.e("FaceDetectCtrl", "reset");
//            if (handle == 0) {
//                return;
//            }
//            faceDetectJni.nativeReset(handle);
//        }
//    }


    public void setStop(boolean stop) {
        isStop = stop;
    }

    public DetectQualityInfo detect(int imageMode, List<LandmarkProto.NormalizedLandmark> landmarks, int width, int height) {
        synchronized (FaceDetectCtrl.class) {
            if(isStop){
                return null;
            }
            Log.e("FaceDetectCtrl", "detect");
            double[] pointsArray = new double[landmarks.size() * 3];
            for (int i = 0; i < landmarks.size(); i++) {
                pointsArray[3 * i] = landmarks.get(i).getX();
                pointsArray[3 * i + 1] = landmarks.get(i).getY();
                pointsArray[3 * i + 2] = landmarks.get(i).getZ();
            }

            float[] faceQualityInfo = faceDetectJni.nativeStartDetect(pointsArray, width, height);
            DetectQualityInfo bean = new DetectQualityInfo();
            if (faceQualityInfo != null) {
//                bean.setFaceID((int) faceQualityInfo[0]);
//                bean.setOriginalImageSize(new Point((int) faceQualityInfo[1],
//                        (int) faceQualityInfo[2]));
//                bean.setFaceRect(new Rect((int) faceQualityInfo[3],
//                        (int) faceQualityInfo[4],
//                        (int) faceQualityInfo[5],
//                        (int) faceQualityInfo[6]));
//                bean.setFaceConfidence(faceQualityInfo[7]);
//                bean.setFaceQuality(faceQualityInfo[8]);
//                bean.setFacePitch(faceQualityInfo[9]);
//                bean.setFaceYaw(faceQualityInfo[10]);
//                bean.setFaceRoll(faceQualityInfo[11]);
//                bean.setCoverMouth(faceQualityInfo[12] == 1F);
//                bean.setCoverEye(faceQualityInfo[13] == 1F);
//                bean.setBlockEye(faceQualityInfo[14] == 1F);
                //左眼状态，右眼状态
                bean.setBlockEye(faceQualityInfo[0] == 1 && faceQualityInfo[1] == 1);
                //头部欧拉角
                bean.setFacePitch(faceQualityInfo[2]);
                bean.setFaceYaw(faceQualityInfo[3]);
                bean.setFaceRoll(faceQualityInfo[4]);
                //头部占比矩形框
                float[] headRateData = {formatNum(faceQualityInfo[5]),
                        formatNum(faceQualityInfo[6]),
                        formatNum(faceQualityInfo[7]),
                        formatNum(faceQualityInfo[8])};
//                float[] headRateData = {faceQualityInfo[5],
//                        faceQualityInfo[6],
//                        faceQualityInfo[7],
//                        faceQualityInfo[8]};
                bean.setHeadRate(headRateData);
                //脸部占比矩形框
                float[] faceRateData = {formatNum(faceQualityInfo[9]),
                        formatNum(faceQualityInfo[10]),
                        formatNum(faceQualityInfo[11]),
                        formatNum(faceQualityInfo[12])};
//                float[] faceRateData = {faceQualityInfo[9],
//                        faceQualityInfo[10],
//                        faceQualityInfo[11],
//                        faceQualityInfo[12]};
                bean.setFaceRate(faceRateData);
                //脸部宽度占比
                bean.setFaceWidthRate(faceQualityInfo[13]);
                Log.d("yeqing","人脸检测信息："+ Arrays.toString(faceQualityInfo));
//                Log.d("yeqing","头部占比矩形框："+ Arrays.toString(headRateData));
//                Log.d("yeqing","脸部占比矩形框："+ Arrays.toString(faceRateData));
                return bean;
            }

            return null;
        }
    }

//    public DetectQualityInfo detect(int imageMode, List<LandmarkProto.NormalizedLandmark> landmarks, int width, int height) {
//        synchronized (FaceDetectCtrl.class) {
//            if(isStop){
//                return null;
//            }
//            Log.e("FaceDetectCtrl", "detect");
//            double[] pointsArray = new double[landmarks.size() * 3];
//            for (int i = 0; i < landmarks.size(); i++) {
//                pointsArray[3 * i] = landmarks.get(i).getX();
//                pointsArray[3 * i + 1] = landmarks.get(i).getY();
//                pointsArray[3 * i + 2] = landmarks.get(i).getZ();
//            }
//            Bitmap bmp = BitmapFactory.decodeFile(ImageUtil.getSaveImage(BaseApplication.getContext(),0));
//            float[] faceQualityInfo = faceDetectJni.nativeDetect(bmp,pointsArray, width, height);
//            DetectQualityInfo bean = new DetectQualityInfo();
//            if (faceQualityInfo != null) {
//                //左眼状态，右眼状态
//                bean.setBlockEye(faceQualityInfo[0] == 1 && faceQualityInfo[1] == 1);
//                //头部欧拉角
//                bean.setFacePitch(faceQualityInfo[2]);
//                bean.setFaceYaw(faceQualityInfo[3]);
//                bean.setFaceRoll(faceQualityInfo[4]);
//                //hor_direct
//                bean.setHor_direct(faceQualityInfo[5]);
//                //ver_direct
//                bean.setVer_direct(faceQualityInfo[6]);
//                //x_position
//                bean.setX_position(faceQualityInfo[7]);
//                //y_position
//                bean.setY_position(faceQualityInfo[8]);
//                //face_distance
//                bean.setFace_distance(faceQualityInfo[9]);
//                //light_status
//                bean.setLight_status(faceQualityInfo[10]);
//                //脸部宽度占比
//                bean.setFaceWidthRate(faceQualityInfo[11]);
//                //图片宽
//                bean.setWidth(faceQualityInfo[12]);
//                //图片高
//                bean.setHeight(faceQualityInfo[13]);
//                Log.d("yeqing","人脸检测信息："+ Arrays.toString(faceQualityInfo));
////                Log.d("yeqing","头部占比矩形框："+ Arrays.toString(headRateData));
////                Log.d("yeqing","脸部占比矩形框："+ Arrays.toString(faceRateData));
//                return bean;
//            }
//
//            return null;
//        }
//    }

    /**保留两位小数*/
    public float formatNum(float orignalNum){
        float num = new BigDecimal(orignalNum).setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
        return num;
    }

//    public int getDetectStatus() {
//        synchronized (FaceDetectCtrl.class) {
//            Log.e("FaceDetectCtrl", "getDetectStatus");
//            if (handle == 0) {
//                return 0;
//            }
//            return faceDetectJni.nativeGetDetectStatus(handle);
//        }
//    }

//    public void setConfig(float face_max_offset_scale,float face_eye_occlusion,
//                          float face_mouth_occlusion,float face_yaw,float face_pitch,float face_max_brightness,
//                          float face_min_brightness,float face_min_size_ratio,float face_max_size_ratio,float face_motion_blur,
//                          float face_gaussian_blur,float face_center_rectX,float face_center_rectY,int need_holding) {
//        synchronized (FaceDetectCtrl.class) {
//            Log.e("FaceDetectCtrl", "setConfig");
//            if (handle == 0) {
//                return;
//            }
//            faceDetectJni.nativeSetConfig(handle, face_max_offset_scale, face_eye_occlusion,
//                    face_mouth_occlusion, face_yaw, face_pitch, face_max_brightness,
//                    face_min_brightness, face_min_size_ratio, face_max_size_ratio, face_motion_blur,
//                    face_gaussian_blur, face_center_rectX, face_center_rectY, need_holding);
//        }
//    }

}
